package com.wmh.baseservice.merchant.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wmh.baseservice.common.annotation.parameterverify.ParameterVerify;
import com.wmh.baseservice.common.utils.CommUtil;
import com.wmh.baseservice.common.utils.page.pojo.PageInfo;
import com.wmh.baseservice.common.utils.page.pojo.PageResult;
import com.wmh.baseservice.common.utils.page.util.PageUtil;
import com.wmh.baseservice.common.utils.returnbody.ResultCodeInfo;
import com.wmh.baseservice.common.utils.returnbody.ReturnBody;
import com.wmh.baseservice.merchant.pojo.MerchantApply;
import com.wmh.baseservice.merchant.pojo.MerchantBankCard;
import com.wmh.baseservice.merchant.pojo.MerchantInfo;
import com.wmh.baseservice.merchant.service.MerchantApplyService;
import com.wmh.baseservice.merchant.service.MerchantBankCardService;
import com.wmh.baseservice.merchant.service.MerchantInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * @author wmh generator
 * @since 2022-01-07
 */
@Api(tags = "商家端-提现申请相关接口")
@RestController
@RequestMapping(value = "merchant/merchantApply", produces = "text/plain;charset=utf-8")
@RequiresRoles("merchant")
public class MerchantApplyController {

    @Resource
    private MerchantApplyService merchantApplyService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private MerchantBankCardService merchantBankCardService;
    @Resource
    private MerchantInfoService merchantInfoService;

    @ApiOperation("提现列表")
    @PostMapping("list")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    public String auditList(PageInfo pageInfo, Long id, Integer sort,String cardNum, String remark, Integer status, String createTimeScope, String auditTimeScope) {
        Long merchantId = (Long) request.getAttribute("id");
        // 设置分页排序规则
        PageUtil.setPageSortRoles(pageInfo,sort,"create_time");
        //执行分页辅助工具
        PageResult<MerchantApply> pageResult = new PageUtil<MerchantApply>(pageInfo).startPage((page, queryWrapper) -> {
            queryWrapper.eq(MerchantApply.MERCHANT_ID, merchantId);
            if (CommUtil.checkNull(id)) {
                queryWrapper.eq(MerchantApply.BANK_CARD_ID, id);
            }
            if(CommUtil.checkNull(remark)){
                queryWrapper.like(MerchantApply.REMARK,remark);
            }
            if(CommUtil.checkNull(status)){
                queryWrapper.eq(MerchantApply.STATUS,status);
            }
            if(CommUtil.checkNull(createTimeScope)){
                List<String> list = JSON.parseArray(createTimeScope, String.class);
                queryWrapper.between(MerchantApply.CREATE_TIME,list.get(0),list.get(1));
            }
            if(CommUtil.checkNull(auditTimeScope)){
                List<String> list = JSON.parseArray(auditTimeScope, String.class);
                queryWrapper.between(MerchantApply.AUDIT_TIME,list.get(0),list.get(1));
            }
            merchantApplyService.page(page, queryWrapper);
        });
        pageResult.getList().forEach(item -> {
            MerchantBankCard merchantBankCard = merchantBankCardService.getByIdForUpdate(item.getBankCardId());
            if(merchantBankCard == null){
                item.setCardName("丢失");
                item.setCardNum("丢失");
                return;
            }
            item.setCardName(merchantBankCard.getCardName());
            item.setCardNum(merchantBankCard.getCardNum());
        });
        if(CommUtil.checkNull(cardNum)){
            List<MerchantApply> list = pageResult.getList().stream().filter(e -> {
                return e.getCardNum().contains(cardNum);
            }).collect(toList());
            pageResult.setList(list);
        }
        return ReturnBody.success(pageResult);
    }

    @ApiOperation("详情")
    @PostMapping("detail")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    @ParameterVerify(notNull = "id")
    public String detail(Long id) {
        JSONObject object = new JSONObject(true);
        MerchantApply merchantApply = merchantApplyService.getByIdForUpdate(id);
        if (!CommUtil.checkNull(merchantApply)) {
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        object.put("apply", merchantApply);
        MerchantBankCard merchantBankCard = merchantBankCardService.getByIdForUpdate(merchantApply.getBankCardId());
        object.put("card", merchantBankCard);
        return ReturnBody.success(object);
    }

    @ApiOperation("提交申请")
    @PostMapping("apply")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", dataTypeClass = Long.class, name = "id", value = "id", required = false),
    })
    @ParameterVerify(notNull = {"cardId", "money"})
    public String apply(Long cardId, BigDecimal money,String remark) {
        Long id = (Long) request.getAttribute("id");
        MerchantBankCard merchantBankCard = merchantBankCardService.getByIdForUpdate(cardId);
        if (!CommUtil.checkNull(merchantBankCard)){
            return ReturnBody.error(ResultCodeInfo.PARAM_ERROR);
        }
        if (!merchantBankCard.getMerchantId().equals(id)){
            return ReturnBody.error(ResultCodeInfo.NO_AUTHORITY_OPERATE_PERMISSION);
        }
        MerchantApply raw = merchantApplyService.getOneForUpdate(new QueryWrapper<MerchantApply>().eq(MerchantApply.MERCHANT_ID, id).eq(MerchantApply.STATUS, 0));
        if (CommUtil.checkNull(raw)){
            return ReturnBody.error("您有一个提现申请正在审核中，请等待管理员审核通过后再操作");
        }
        MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(id);
        if (merchantInfo.getBalance().compareTo(money) < 0){
            return ReturnBody.error("余额不足");
        }
        MerchantApply merchantApply = new MerchantApply().setBankCardId(cardId).setMerchantId(id).setStatus(0).setMoney(money).setRemark(remark);
        merchantApplyService.apply(merchantApply,merchantInfo);
        return ReturnBody.success();
    }
}
